<?php
    namespace App\Services\Pay;

    use Input, Log, Queue;
    use App\Services\Tool\DataBase\SQL;
    use App\Services\Tool\GeneralTool;
    use App\Services\Tool\Order\OrderTool;
    use App\Services\Tool\Pay\PayTool;
    use App\Services\Tool\Pay\AlipayTool;
    use App\Services\Tool\Pay\UnionPayTool;
    use App\Services\Tool\Statistics\IncomeTool;
    // use App\Jobs\PostOrder;

    class PayApi{

        function __construct(AlipayTool $alipayTool,
                             OrderTool $orderTool,
                             PayTool $payTool,
                             UnionPayTool $unionTool,
                             IncomeTool $incomeTool){
            $this->alipayTool   = $alipayTool;
            $this->orderTool    = $orderTool;
            $this->payTool      = $payTool;
            $this->unionTool    = $unionTool;
            $this->incomeTool   = $incomeTool;
        }

        /**
            优惠券支付
            参数：
                user_id         用户编号
                order_id        订单编号
                platform        平台
         */
        function couponPay($input){
            try{
                //判断参数是否存在
                if(!isset($input['user_id'])||!isset($input['order_id'])||!isset($input['platform'])){
                    return GeneralTool::createResult('','M00002');
                }

                //判断参数是否足够
                if(!isset($input['order_id'])||!isset($input['user_id'])||!isset($input['platform'])){
                    return GeneralTool::createResult('','M00002');
                }

                $order = $this->orderTool->get_order_pay_info($input);


                if($order['state'] != 'M00000' && $order['state'] != 'M05020') return GeneralTool::createResult('',$order['state']);
                if(isset($input['platform'])) $this->orderTool->update_order_platform($input);
                if($order['state'] == 'M00000' && $order['data']['total_fee'] > 0) return GeneralTool::createResult('','M05020');
                $input['total_fee'] = 0;
                //订单支付成功操作
                $result = $this->orderTool->order_pay_success($input,3);

                return GeneralTool::createResult('','M00000');
            }catch(\Exception $e){
                Log::info($e);
                SQL::CatchDo();
                return GeneralTool::createResult('','M00003');
            }finally{
                SQL::FinallyDo();
            }
        }

        /**
            支付宝支付
            参数：
                user_id         用户编号
                order_id        订单编号
                platform        平台
         */
        function alipay($input){
            try{
                //判断参数是否足够
                if(!isset($input['order_id'])||!isset($input['user_id'])||!isset($input['platform'])){
                    return GeneralTool::createResult('','M00002');
                }

                $order = $this->orderTool->get_order_pay_info($input);

                if($order['state'] != 'M00000') return GeneralTool::createResult('',$order['state']);
                if(isset($input['platform'])) $this->orderTool->update_order_platform($input);

                $input['out_trade_no'] = $input['order_id'];
                $input['total_fee'] = $order['data']['total_fee'];
                $input['subject'] = 'Mytee商城商品';
                $input['body'] = 'Mytee商城商品';

                $result = $this->payTool->alipay($input);

                if($result['order_info'] == '') return GeneralTool::createResult('','M05021');

                return GeneralTool::createResult($result,'M00000');
            }catch(\Exception $e){
                Log::info($e);
                SQL::CatchDo();
                return GeneralTool::createResult('','M00003');
            }finally{
                SQL::FinallyDo();
            }
        }

        /**
            支付宝网页支付
            参数：
                user_id         用户编号
                order_id        订单编号
                platform        平台
         */
        function alipay_web($input){
            try{
                //判断参数是否足够
                if(!isset($input['order_id'])||!isset($input['user_id'])||!isset($input['platform'])){
                    return GeneralTool::createResult('','M00002');
                }

                $order = $this->orderTool->get_order_pay_info($input);

                if($order['state'] != 'M00000') return GeneralTool::createResult('',$order['state']);
                if(isset($input['platform'])) $this->orderTool->update_order_platform($input);

                $input['out_trade_no'] = $input['order_id'];
                $input['total_fee'] = $order['data']['total_fee'];
                $input['subject'] = 'Mytee商城商品';
                $input['body'] = 'Mytee商城商品';

                return GeneralTool::createResult($input, 'M00000');
            }catch(\Exception $e){
                Log::info($e);
                SQL::CatchDo();
                return GeneralTool::createResult('','M00003');
            }finally{
                SQL::FinallyDo();
            }
        }

        /**
            微信支付
            参数：
                user_id         用户编号
                order_id        订单编号
                trade_type      支付类型
                platform        平台
         */
        function wxPay($input){
            try{
                if(!isset($input['order_id'])||!isset($input['user_id'])||!isset($input['trade_type'])||!isset($input['platform'])){
                    return GeneralTool::createResult('','M00002');
                }
                $order = $this->orderTool->get_order_pay_info($input);

                if($order['state'] != 'M00000') return GeneralTool::createResult('',$order['state']);
                if(isset($input['platform'])) $this->orderTool->update_order_platform($input);

                $input['trade_type'] = empty($input['trade_type'])?'APP':$input['trade_type'];
                $input['out_trade_no'] = $input['order_id'];
                $input['total_fee'] = $order['data']['total_fee'];
                $input['body'] = 'Mytee商城商品';
                $input['attach'] = 'Mytee商城商品';

                $result = $this->payTool->wxpay($input);

                return $result;

            }catch(\Exception $e){
                Log::info($e);
                SQL::CatchDo();
                return GeneralTool::createResult('','M00003');
            }finally{
                SQL::FinallyDo();
            }
        }


        /**
            回调
         */

        /**
            支付宝回调
         */
        function AlipayNotify($input){
            Log::info('------------支付宝回调--------');
            Log::info($input);
            if(SQL::count(array('table'=>'orders',
                                'where'=>array('trade_no'=>$input['trade_no'])))==1&&
               SQL::count(array('table'=>'back_alipays',
                                'where'=>array('trade_no'=>$input['trade_no'])))==1){
                return 'success';
            }


            $re         = SQL::first(array('table'=>'alipay',
                                           'where'=>array()));
            $url        = 'https://mapi.alipay.com/gateway.do?service=notify_verify&partner='.$re->partner.
                          '&notify_id='.$input['notify_id'];
            $ch         = curl_init ($url);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, 1);
            $response   = curl_exec($ch);
            //if($response!='true'){
            //  return 'hehe';
            //}
            if($input['trade_status']=='TRADE_SUCCESS'){
                $order_id   = $input['out_trade_no'];
                $rex        = SQL::first(array('table'=>'orders',
                                               'where'=>array('order_id'=>$input['out_trade_no'])));

                if(!isset($rex)){
                    return 'fail';
                }

                $veryfy = $this->alipayTool->getSignVeryfy($input,$input['sign'],$re);
                Log::info($veryfy);
                if(!$veryfy) return 'hehe';

                try{
                    //订单支付成功操作
                    $result = $this->orderTool->order_pay_success($input,2);

                    SQL::insert(array('table'=>'back_alipays',
                                      'insert'=>$input));
                }catch(\Exception $e){
                    Log::info($e);
                }


                //Queue::push(new PostOrder(1,['order_id'=>$rex->order_id]));
                //$this->orderTool->postOrderToAdsense(['order_id'=>$rex->order_id]);
            }else{
                return 'fail';
            }

            return 'success';

        }

        /**
            微信回调
         */
        function weixinNotify($input){
            $input            = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
            Log::info('微信回调');
            Log::info($input);

            //Log::info($input);
            if(SQL::count(array('table'=>'orders',
                                'where'=>array('trade_no'=>$input['transaction_id'])))==1&&
               SQL::count(array('table'=>'back_weixins',
                                'where'=>array('transaction_id'=>$input['transaction_id'])))==1){
                $result   = '<xml><return_code>'.$input['return_code'].'</return_code><return_msg>OK</return_msg></xml>';
                return $result;
            }


            $order_id       = substr($input['out_trade_no'],0,-5);

            $rex            = SQL::first(array('table'=>'orders',
                                               'where'=>array('order_id'=>$order_id)));
            if(!isset($rex)){
                return '<xml><return_code>'.$input['return_code'].'</return_code><return_msg>'.$input['return_msg'].'</return_msg></xml>';
            }

            $wei            = PayTool::getWeixinInfo($input);

            $wei->notify_url      = 'http://'.$_SERVER['HTTP_HOST'].$wei->notify_url;
            //验证是否是微信支付返回的数据
            $sig            = 'appid='.$input['appid'].'&mch_id='.$input['mch_id'].'&nonce_str='.$input['nonce_str'].'&transaction_id='.$input['transaction_id'].
                              '&key='.$wei->key;
            $sign       = strtoupper(md5($sig));
            $str            = '<xml><appid>'.$input['appid'].'</appid><mch_id>'.$input['mch_id'].'</mch_id><nonce_str>'.$input['nonce_str'].
                              '</nonce_str><transaction_id>'.$input['transaction_id'].'</transaction_id><sign>'.$sign.'</sign></xml>';
            $url            = 'https://api.mch.weixin.qq.com/pay/orderquery'; //接收xml数据的文件
            $header[]       = "Content-type: text/xml";//定义content-type为xml,注意是数组
            $ch             = curl_init ($url);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS, $str);
            $response       = curl_exec($ch);
            $return         = (array)simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
            Log::info($return);
            if($return['return_code']!='SUCCESS'){
                return;
            }

            if($input['return_code']=='SUCCESS'){
                try{
                    //订单支付成功操作
                    $result = $this->orderTool->order_pay_success($input,1);


                    SQL::insert(array('table'=>'back_weixins',
                                      'insert'=>$input));

                    //Queue::push(new PostOrder(1,['order_id'=>$rex->order_id]));
                    //$this->orderTool->postOrderToAdsense(['order_id'=>$rex->order_id]);
                }catch(\Exception $e){
                    Log::info($e);
                }

            }else{
                return '<xml><return_code>'.$input['return_code'].'</return_code><return_msg>'.$input['return_msg'].'</return_msg></xml>';
            }

            Log::info($return);
            $result       = '<xml><return_code>'.$input['return_code'].'</return_code><return_msg>OK</return_msg></xml>';
            return $result;
        }

        /**
            代付回调
         */
        function transfer_accounts_notify($input){
            Log::info($input);
            // $input = $this->unionTool->convertResultStringToMap($input);
            $verfy = $this->unionTool->validate($input);
            Log::info($verfy);
            if($verfy){
                $result = $this->incomeTool->transfer_accounts_notify(['withdraw_number' => $input['orderId'], 'trade_no' => $input['queryId']]);
                if($result) $this->incomeTool->apply_withdraw_success_push(['withdraw_number' => $input['orderId']]);
            }
        }


        /**
         * 支付宝退款回调
         */
        function alirefund_notify($input){
            if(!isset($input['notify_id'])){
                return '参数不足';
            }

            //dd(explode('^',$input['result_details']));
            $url        = 'https://mapi.alipay.com/gateway.do?';
            $str        = 'service=notify_verify&partner='.env('alipay_pid').'&notify_id='.$input['notify_id'];
            $ch         = curl_init ($url);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HEADER, 0);// 过滤HTTP头
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
            curl_setopt($ch, CURLOPT_POST, 1);
            $response   = curl_exec($ch);
            //dd($response,$str);
            curl_close($ch);
            Log::info($input);
            Log::info($response);

            if($response!='true'){
                return 'hehe';
            }

            if($input['success_num']>0){

                //成功
                if(strpos($input['result_details'],'#')){
                    //多条记录
                }else{

                    //一条记录
                    $arr     = explode('^',$input['result_details']);

                    if(in_array('success',$arr)||in_array('SUCCESS',$arr)){
                        //var_dump($arr[0]);
                        /*
                        $result = $this->bailTool->updBail(array('trade_no'=>$arr[0],
                                                                 'need_back'=>1,
                                                                 'is_pay'=>2),
                                                           array('is_back'=>2,
                                                                 'batch_no'=>$input['batch_no']));
                        */
                        $input['order_id'] = SQL::pluck(['table' => 'orders',
                                                         'where' => ['trade_no' => $arr[0]],
                                                         'pluck' => 'order_id']);
                        $input['iden'] = 0;
                        $cancel = OrderTool::order_cancel($input,2);
                    }
                }
            }else{
                //失败
            }
            return 'success';
        }

        /**
         *  工具
         */
        function test($input){

        }

    }
